package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.WeChatConstant;
import com.sky.exception.BaseException;
import com.sky.service.WechatService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信登录实现类
 *
 * @Author mr.lcc
 * @Data 2025/5/23 21:31
 */
@Service
public class WechatServiceImpl implements WechatService {

    /**
     * 小程序appId
     */
    @Value("${sky.wechat.appid}")
    private String appId;

    /**
     * 小程序appSecret
     */
    @Value("${sky.wechat.secret}")
    private String appSecret;


    /**
     * 根据微信登录code获取openId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        // 1.组装请求参数
        Map<String, String> map = getBaseParams();
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        // 2.进行查询openId
        String resultJSON = HttpClientUtil.doGet(WeChatConstant.GET_OPEN_ID_URL, map);

        // 3.判断响应的openId是否为空
        if (!StringUtils.hasLength(resultJSON)) {
            throw new BaseException("微信登录获取openId失败");
        }

        // 4.解析响应结果
        JSONObject jsonObject = JSON.parseObject(resultJSON);
        Integer errcode = jsonObject.getInteger("errcode");
        if (errcode != null && errcode != 0) {
            throw new BaseException("微信登录获取openId失败");
        }

        // 5.返回openId
        return jsonObject.getString("openid");
    }

    /**
     * 根据微信登录code获取手机号
     *
     * @param code
     * @return
     */
    @Override
    public String getPhone(String code) {
        return "";
    }

    /**
     * 获取微信登录的access_token
     * TODO
     *
     * @return
     */
    public String getAccessToken() {
        return "";
    }

    /**
     * 获取基础微信登录的参数
     *
     * @return
     */
    private Map<String, String> getBaseParams() {
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", appSecret);
        return map;
    }
}
